//
//  ValidatorBindingController.swift
//  SCA
//
//  Created by tjun on 2025/9/6.
//

import SnapKit

class MainButton: GradientButton {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setTitleColor(.white, for: .normal)
        setTitleColor(.white.withAlphaComponent(0.5), for: .disabled)
        colors = [UIColorMake(0x05D4FC), UIColorMake(0xBE0DEF), UIColorMake(0xF202D3)]
        locations = [0, 0.5, 1]
        setStartPoint(CGPoint(x: 0, y: 0.5), endPoint: CGPointMake(1, 0.5))
        isGradientBorder = false
        layer.cornerRadius = AppStyle.cornerRadius.normal
        layer.masksToBounds = true
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

class ValidatorBindingController: BaseController {

    private var shareLinkUrl: String = ""
    private let linkLabel = UILabel(font: UIFontMediumMake(14), textColor: UIColorMake(0xCCCCCC))
    private let otpTextField = LabeledTextField(tip: "请输入绑定号的2FA验证码".localizedString)
    private let confirmButton = MainButton(type: .system, title: "确认".localizedString, font: UIFontMake(16), textColor: .white)
    private let qrCodeImageView = UIImageView()
    private let linkView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationBar.title = "2FA验证器绑定".localizedString
        
        view.addSubview(qrCodeImageView)
        qrCodeImageView.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.top.equalTo(navBarHeight + 20)
            make.width.height.equalTo(124)
        }
 
        let titleLabel = UILabel(text: "2FA验证器".localizedString, font: UIFontSemiboldMake(14), textColor: .white).addTo(view)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(qrCodeImageView)
            make.left.equalTo(qrCodeImageView.snp.right).offset(12)
        }

        let tipLabel = UILabel(text: "请使用您首选的2FA身份验证应用扫描此QR码。".localizedString, font: UIFontMediumMake(13), textColor: .white).addTo(view)
        tipLabel.numberOfLines = 0
        tipLabel.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(5)
            make.left.equalTo(qrCodeImageView.snp.right).offset(12)
            make.right.equalTo(-20)
        }
 
        let copyView = addCopyLinkView().addTo(view)
        copyView.addCorner(radius: 10)
        copyView.isHidden = true
        copyView.snp.makeConstraints { make in
            make.left.equalTo(titleLabel)
            make.right.equalTo(-20)
            make.bottom.equalTo(qrCodeImageView)
        }
        
        otpTextField.titleAttributedText = "2FA OTP*".attributedString(rangeString: "*", rangeColor: UIColorMake(0xFF0000))
        view.addSubview(otpTextField)
        otpTextField.textField.addTarget(self, action: #selector(textFieldDidChange(_ :)), for: .editingChanged)
        otpTextField.snp.makeConstraints { make in
            make.top.equalTo(qrCodeImageView.snp.bottom).offset(20)
            make.left.right.equalToSuperview().inset(20)
        }
        
        confirmButton.addTo(view)
        confirmButton.isEnabled = false
        confirmButton.addTarget(self, action: #selector(confirmButtonTapped), for: .touchUpInside)
        confirmButton.snp.makeConstraints { make in
            make.left.right.equalTo(otpTextField)
            make.height.equalTo(AppStyle.size.buttonHeight.scaled)
            make.top.equalTo(otpTextField.snp.bottom).offset(40)
        }
        
        loadData()
    }
    
    private func addCopyLinkView() -> UIView {
        linkView.backgroundColor = UIColorMake(0x2E3036)
        
        let copyButton = UIButton(image: UIImage(named: "share_copy"), target: self, action: #selector(copyButtonTapped)).addTo(linkView)
        copyButton.snp.makeConstraints { make in
            make.right.equalTo(-10)
            make.centerY.equalToSuperview()
            make.height.width.equalTo(20)
        }
        
        linkLabel.addTo(linkView)
        linkLabel.numberOfLines = 0
        linkLabel.snp.makeConstraints { make in
            make.right.equalTo(copyButton.snp.left).offset(-20)
            make.left.equalTo(10)
            make.top.equalToSuperview().offset(6)
            make.bottom.equalToSuperview().offset(-6)
        }
        
        return linkView
    }
    
    @objc func textFieldDidChange(_ sender: UITextField) {
        if let otp = otpTextField.textField.text, otp.count > 0 {
            confirmButton.isEnabled = true
        } else {
            confirmButton.isEnabled = false
        }
    }
    
    func loadData() {
        MineService.load2FAValidatorData { qrCodeLinkUrl, code in
            guard let linkUrl = qrCodeLinkUrl,
                  let code = code else {
                return
            }
            self.linkView.isHidden = false
            self.qrCodeImageView.setImage(url: linkUrl)
            self.shareLinkUrl = code
            self.linkLabel.text = code
        }
    }
 
    @objc func confirmButtonTapped() {
        
        guard let otp = otpTextField.textField.text, otp.count > 0 else {
            return
        }
        
        view.endEditing(true)
        HUD.showLoadingInView(self.view)
        MineService.bind2FAValidator(otp: otp, success: {
            HUD.showMessage("绑定成功".localizedString)
             self.navigationController?.popViewController(animated: true)
        })
        
    }
    
    @objc func copyButtonTapped() {
        UIPasteboard.general.string = UserInfo.username
        HUD.showMessage("复制成功".localizedString)
    }

}
